package com.wanxi.servlet.other;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;

@WebServlet("/request1")
public class MyServlet02 extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(req.getContextPath());   //项目名称
        System.out.println(req.getRequestURL());    //全路径
        System.out.println(req.getRequestURI());    //一半的路径
        System.out.println(req.getParameter("username"));   //打印username的值
        System.out.println(req.getParameter("password"));   //打印password的值
        System.out.println(req.getMethod());    //打印方法
//        System.out.println(req.getParameterValues("username").toString()); //打印参数的地址
        req.getParameterMap().forEach((key, value) -> {    //打印请求参数(map方式)
            System.out.println(key + "===" + value[0]);
        });
//        将参数传入req中
        String username = new String();
        String password = new String();
        HttpSession session = req.getSession();
        if (req.getParameter("username") != null && req.getParameter("password") != null) {
            username = req.getParameter("username");
            password = req.getParameter("password");
            session.setAttribute("username", username);
            session.setAttribute("password", password);
        }

        req.setAttribute("username", username);
        req.setAttribute("password", password);
//        转发（转发时要将service的req和resp发送到新页面,仅仅在转发时可以拿到数据）
            req.getRequestDispatcher("home.jsp").forward(req,resp);
//        通过session去将数据转发到新页面，只能在同一个浏览器才能拿到数据，且数据保存时长为30分钟）
//        resp.sendRedirect("home.jsp");
//        通过servlet去将数据转发到新页面，只能在同一台电脑上才能拿到数据，数据保存时间由浏览器决定

    }
}
//public class MyServlet02{
//    void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
//        String username=req.getParameter("username");
//        String password=req.getParameter("password");
//        System.out.println(username+" : "+password);
//        req.setAttribute("username",username);
//        req.setAttribute("password",password);
//        req.getRequestDispatcher("home.jsp").forward(req,resp);
//
//    }
//}
